package dockerCore

import (
	"bufio"
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	client2 "image-pull/client"
	"io"
	"time"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

type DockerInfo struct {
	ImageName string
	UserName  string
	Password  string
}

func (d DockerInfo) PullImage(n int, nodeIp string) (err error) {
	var (
		encodedJSON []byte
		cli         *client.Client
	)
	ctx := context.Background()
	if cli, err = client2.GetClient(); err != nil {
		return fmt.Errorf("获取docker客户端失败：%s", err)
	}
	if encodedJSON, err = json.Marshal(types.AuthConfig{ //序列化docker认证信息
		Username: d.UserName,
		Password: d.Password,
	}); err != nil {
		return fmt.Errorf("docker认证信息序列化失败：%s", err)
	}
	for i := 0; i < 3; i++ {
		fmt.Printf("开始拉取镜像 %s \n", d.ImageName)
		pullReader, err := cli.ImagePull(
			ctx,
			d.ImageName,
			types.ImagePullOptions{
				RegistryAuth: base64.URLEncoding.EncodeToString(encodedJSON),
			})
		if err != nil {
			err = fmt.Errorf("th %d, 重试 %d,镜像拉取失败：%s", n, i, err)
			fmt.Println(err)
			time.Sleep(time.Second)
			continue
		}
		defer pullReader.Close()
		//读取docker pull的输出
		reader := bufio.NewReader(pullReader)
		for {
			outPut, err := reader.ReadString('\n') //按照字符’\n‘来分割每次读取长度
			if err != nil {
				if err == io.EOF {
					fmt.Println("读完了")
					break
				}
				fmt.Printf("read from dockerpull Out failed, err:%v\n", err)
				continue
			}

			if err = client2.TcpSend(client2.TcpClient, fmt.Sprintf("%s-%s", nodeIp, outPut)); err != nil {
				fmt.Printf("发送数据失败, err:%v\n", err)
				break
			}
		}
		break
	}
	return
}
